#pragma once

#include "Acceptor.h"
#include "EventLoop.h"
#include "LoopThreadPool.h"
#include "Connection.h"
#include <cstdint>
#include <functional>
#include <unordered_map>
#include <string>

namespace muduo{
    class TcpServer{
    private:
        int _port;              //服务器端口号
        EventLoop _baseloop;    //监听套接字的EventLoop
        LoopThreadPool _pool;   //线程池
        Acceptor _accepter;     //监听套接字的Accepter
        uint64_t _next_id;      //定时器id与connection编号
        int _timeout;           //定时任务执行时间
        std::unordered_map<uint64_t, PtrConnection> _conns; //管理连接的map
        bool _inactive_release; //非活跃连接销毁设置
        

        using ConnectedCallback = std::function<void(const PtrConnection&)>;
        using MessageCallback = std::function<void(const PtrConnection&,Buffer*)>;
        using CloseCallback = std::function<void(const PtrConnection&)>;
        using AnyEventCallback = std::function<void(const PtrConnection&)>;
        using Functor = std::function<void()>;
        ConnectedCallback _connected_callback;  //连接建立后的回调函数
        MessageCallback _message_callback;      //处理收到的信息的回调函数
        CloseCallback _close_callback;          //关闭连接回调函数
        AnyEventCallback _anyevent_callback;    //任意事件回调函数
        CloseCallback _server_close_callback;
    private:
        void consinsert(const PtrConnection& con);  //向map中插入新的connection
        void NewConnection(int newfd);              //用监听到的新的文件描述符创建连接
        void RunAfterInLoop(const Functor& func,int delay); //设置定时器任务
        void RemoveConnectionInLoop(const PtrConnection& con);  //移除连接
    public:
        TcpServer(int port);
        void RunAfter(const Functor& func,int delay);   
        void SetPoolNum(int num);                                   //设置线程池大小
        void SetConnectedCallback(const ConnectedCallback& conc); 
        void SetMessageCallback(const MessageCallback& mesc);          
        void SetCloseCallback(const CloseCallback& closc);            
        void SetAnyEventCallback(const AnyEventCallback& anyc);
        void SetSvrCloseCallback(const CloseCallback& closc);
        void SetInactiveRelease(int timeout);                       //设置非活跃连接销毁
        void RemoveConnection(const PtrConnection& con);            //移除连接
        void start();               //启动服务器
    };
}